package myky.com.doctorapp.utils

import android.app.FragmentManager
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import myky.com.doctorapp.wight.LoadingDialog

/**
 * Description: 
 * @author xiangyao
 * Created by 2019/4/12 10:52 AM
 */
class ProgressTransformer<T>(fragmentManager: FragmentManager, message: String) : ObservableTransformer<T, T> {

    private var loadingDialog: LoadingDialog? = null

    private val subject: Subject<Boolean> = PublishSubject.create()

    private var fr:FragmentManager?=null

    private var st:String?=null


    init {
        loadingDialog = LoadingDialog()

        fr=fragmentManager

        st=message


        loadingDialog?.setCancelListener {
            subject.onNext(true)//如果取消隐藏当前Dialog，则解除订阅关系
        }

    }


    override fun apply(upstream: Observable<T>): ObservableSource<T> {


        return upstream.takeUntil(subject.filter {

            it


        }.take(1))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete {
                    hideLoading()

                }
                .doOnError {

                    hideLoading()

                }
                .doOnSubscribe {
                    showLoading()
                }

    }

    private fun showLoading() {
        loadingDialog?.show(fr,st)

    }

    private fun hideLoading() {

        loadingDialog?.dismiss()
    }


}